package com.hsmpay.mobile.ds.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.SendParam;
import com.hsmpay.yl8583.service.RuiShengGTPayService;
import com.hsmpay.common.pojo.BasePojo;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.dao.terminal.TchannelDao;
import com.hsmpay.mobile.dao.terminal.TchannelMDao;
import com.hsmpay.mobile.dao.trans.TransOrderDao;
import com.hsmpay.mobile.ds.DS_RuiShengGTService;
import com.hsmpay.mobile.pojo.terminal.Tchannel;
import com.hsmpay.mobile.pojo.terminal.TchannelM;
import com.hsmpay.mobile.pojo.trans.TransOrder;

/**
 * 瑞晟国通  服务接口 DS_RuiShengGTService
 * @author 颜铃璋
 * 创建时间：2014-8-7
 */
@Service("ds_RuiShengGTService")
public class DS_RuiShengGTServiceImpl implements DS_RuiShengGTService<BasePojo,Long> {
	@Resource(name="tchannelDao")
	TchannelDao<Tchannel,Long> tchannelDao;
	@Resource(name="transOrderDao")
	private TransOrderDao<TransOrder,String> transOrderDao;//交易订单
	@Resource(name="tchannelMDao")
	private TchannelMDao<TchannelM,String> tchannelMDao;//通道商户号表
	
	private Long flRoleId = 2l;
	private Long fdRoleId = 3l;
//	private static int cnt = 0;
	private static int ruiShengGT_TchannelId = 38;
	
	/**
	 * 获取ECB银联socket 接口密钥
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public Map<String,String> getMiYao(TchannelM tcm,String str,String transAmt,Double c_fdMoney)throws Exception{
		Map<String,String> miYao = null;
		if(StringUtils.isEmpty(str)){
			miYao = reflushMiYao(tcm,transAmt,c_fdMoney);
		}else{
			miYao = new HashMap<String, String>();
			//if(StringUtils.isEmpty(str)) return reflushMiYao(transAmt,c_fdMoney);
			String[] strA = str.split("_");
			if("-1".equals(strA[0])) return reflushMiYao(tcm,transAmt,c_fdMoney);
			miYao.put("batchId", strA[2]);
			miYao.put("pinKey", strA[3]);
			miYao.put("macKey", strA[4]);
//			miYao.put("trkKey", strA[5]);
		}
		return miYao;
	}
	
	/**
	 * 刷新ECB银联socket 接口密钥
	 * @return
	 * @throws Exception
	 */
	public Map<String,String> reflushMiYao(TchannelM tcm,String transAmt,Double c_fdMoney)throws Exception{
		//TchannelM tcm = getTchannelM(transAmt,c_fdMoney);
		RuiShengGTPayService aps = new RuiShengGTPayService(tcm.getMcode(),tcm.getTcode(),"000001",tcm.getMainKey(),null,null);
		
		Integer bankOrderNum = searchRuiShengGTTransId();
		String miyao = aps.login(bankOrderNum.toString());
		//保存密钥
		tchannelMDao.updateMobileTcOtherById(tcm.getId(), miyao);
		return getMiYao(tcm,miyao,transAmt,c_fdMoney);
	}
	
	/**
	 * 查询ECB银联订单号
	 * @return
	 * @throws Exception
	 */
	public Integer searchRuiShengGTTransId()throws Exception{
		return transOrderDao.searchRuiShengGTTransId();
	}
	
	/**
	 * 余额查询
	 * @param send
	 * @return
	 * @throws Exception
	 */
	public BalanceResult balanceEnquiry(Qian4SendLog send)throws Exception{
		TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(),send.getTerminalId());
		Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),null,null);
		
		RuiShengGTPayService aps = new RuiShengGTPayService(send.getMerchantId(),send.getTerminalId(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("pinKey"),miyao.get("macKey"));//getAnxinybPayService(send.getTransAmt());
		SendParam sendParam = new SendParam();
		BeanUtils.copyProperties(sendParam,send);
		return aps.balanceEnquiry(sendParam);
	}
	
	/**
	 * 费率版收款
	 * @param send
	 * @return
	 * @throws Exception
	 */
	public PurchaseResult billPayment(Qian4SendLog send,Tchannel tc)throws Exception{
		Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee()/tc.getFeeRate()));
		
		TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(),send.getTerminalId());
		Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),send.getTransAmt(),c_fdMoney);
		RuiShengGTPayService aps = new RuiShengGTPayService(send.getMerchantId(),send.getTerminalId(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("pinKey"),miyao.get("macKey"));
		
		SendParam sendParam = new SendParam();
		BeanUtils.copyProperties(sendParam,send);
		PurchaseResult rs = aps.billPayment(sendParam);
//		if("00A0".equals(rs.getReqCode())){
//			miyao = reflushMiYao(send.getTransAmt(),c_fdMoney);
//			rs = aps.billPayment(send);
//		}
		
		//判断商户号是否  收满  ######
//		if(){
//			qihuanJieKou(send.getTransAmt());
//		}
		Integer status = null;
		Double addUseTotal = NumberUtil.roundF2(Integer.parseInt(send.getTransAmt())/100.00);
		Double useTotal = NumberUtil.roundF2((tcm.getUseTotal()+addUseTotal));
		if(null != tcm.getTotalLimit() && tcm.getTotalLimit() < useTotal){
			status = 3;
		}
		if(!("0000".equals(rs.getReqCode()))) addUseTotal = null;
		tchannelMDao.updateTchannelMUseMoney(tcm.getId(), addUseTotal, status);//交易失败也要修改时间
		return rs;
	}
	
	
	/**
	 * 冲正
	 * @param send
	 * @return
	 * @throws Exception
	 */
	public RevocationResult unBillPayment(Qian4SendLog send)throws Exception{
		Tchannel tc = tchannelDao.searchMobileTchannelByCode(send.getCollectionType());
		Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee()/tc.getFeeRate()));
		
		TchannelM tcm = tchannelMDao.searchTchannelMByCode(send.getCollectionType(), send.getMerchantId(),send.getTerminalId());
		
		Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),send.getTransAmt(),c_fdMoney);
		//冲正  重新创建接口对象
		RuiShengGTPayService aps = new RuiShengGTPayService(send.getMerchantId(),send.getTerminalId(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("pinKey"),miyao.get("macKey"));
		
		SendParam sendParam = new SendParam();
		BeanUtils.copyProperties(sendParam,send);
		RevocationResult rr = aps.unBillPayment(sendParam);
//		if("00A0".equals(rr.getReqCode())){
//			miyao = reflushMiYao(send.getTransAmt(),c_fdMoney);
//			rr = aps.unBillPayment(send);
//		}
		return rr;
	}
	
	/**
	 * 获得费率版支付接口
	 * @return
	 * @throws Exception
	 */
	public RuiShengGTPayService getRuiShengGTPayService(String transAmt,Double c_fdMoney)throws Exception{
		TchannelM tcm = getTchannelM(transAmt,c_fdMoney);
		
		Map<String,String> miyao = getMiYao(tcm,tcm.getOtherParam(),transAmt,c_fdMoney);
		//获取主密钥 和 终端号
		return new RuiShengGTPayService(tcm.getMcode(),tcm.getTcode(),miyao.get("batchId"),tcm.getMainKey(),miyao.get("pinKey"),miyao.get("macKey"));
	}
	
	private TchannelM getTchannelM(String transAmt,Double c_fdMoney)throws Exception{
		TchannelM tcm = null;
		Double money = 0.00;
		if(StringUtils.isNotEmpty(transAmt)){
			 money = Integer.parseInt(transAmt)/100.0;
		}
		Long roleId = flRoleId ;
		if(money > c_fdMoney)roleId = fdRoleId;
		List<TchannelM> list = tchannelMDao.searchMobileTCListByCodeOrderByUseTime(ruiShengGT_TchannelId, roleId);
//		tcm = list.get(cnt%list.size());
//		cnt++;
		tcm = list.get(0);//获取第一个
		//更新使用时间 
		tchannelMDao.updateTchannelMUseTime(tcm.getId());
		return tcm;
	}
	
	/**
	 * 初始化 请求参数
	 * @param send
	 * @param tc
	 * @return
	 * @throws Exception
	 */
	public Qian4SendLog initSend(Qian4SendLog send,Tchannel tc)throws Exception{
		Double c_fdMoney = NumberUtil.roundF2((tc.getFdMaxFee()/tc.getFeeRate()));
		RuiShengGTPayService aps = getRuiShengGTPayService(send.getTransAmt(),c_fdMoney);
		
		send.setBankOrderNum(searchRuiShengGTTransId().toString());//查询序列 获取动态流水号
		send.setBatchId(aps.batch);//批次号
		send.setMerchantId(aps.merchantId);
		send.setTerminalId(aps.terminalId);
		return send;
	}
}
